const conn = require('./db.js');
module.exports = {
    getAllHero: (req, res) => {
        const sql = 'select * from user';
        conn.query(sql, (err, result) => {
            if (err) return res.send({ status: 500, msg: err.message, data: null })
            res.send({ status: 200, msg: 'ok', data: result })
        })
    },
    addHero: (req, res) => {
        const hero = req.body
            // 得到当前的时间对象
        const dt = new Date()

        // 字符串，有一个新方法，叫做 padStart(长度, 要填充的字符串)
        const y = dt.getFullYear()
        const m = (dt.getMonth() + 1).toString().padStart(2, '0')
        const d = dt
            .getDate()
            .toString()
            .padStart(2, '0')

        const hh = dt
            .getHours()
            .toString()
            .padStart(2, '0')
        const mm = dt
            .getMinutes()
            .toString()
            .padStart(2, '0')
        const ss = dt
            .getSeconds()
            .toString()
            .padStart(2, '0')
            // 补全英雄的添加时间
        hero.ctime = y + '-' + m + '-' + d + ' ' + hh + ':' + mm + ':' + ss

        // 调用 conn.query 实现 添加英雄
        const sql = 'insert into user set ?'
        conn.query(sql, hero, (err, result) => {
            if (err) return res.send({ status: 500, msg: err.message, data: null })
            res.send({ status: 200, msg: 'ok', data: null })
        })
    },
    getHeroById: (req, res) => {
        const id = req.params.id;
        const sql = 'select * from user where id = ?';
        conn.query(sql, id, (err, result) => {
            if (err) return res.send({ status: 500, msg: err.message, data: null })
            res.send({ status: 200, msg: 'ok', data: result })
        })
    },
    deleteHeroById: (req, res) => {
        const id = req.params.id;
        const sql = 'update user set isdel = 1 where id = ?';
        conn.query(sql, id, (err, result) => {
            if (err) return res.send({ status: 500, msg: err.message, data: null })
            res.send({ status: 200, msg: 'ok', data: null })
        })
    },
    updateHeroById: (req, res) => {
        const id = req.params.id;
        const sql = 'update user set ? where id = ?';
        conn.query(sql, id, (err, result) => {
            if (err) return res.send({ status: 500, msg: err.message, data: null })
            res.send({ status: 200, msg: 'ok', data: null })
        })
    },
    backHeroById: (req, res) => {
        const id = req.params.id;
        const sql = 'update user set isdel = 0 where id = ?';
        conn.query(sql, id, (err, result) => {
            if (err) return res.send({ status: 500, msg: err.message, data: null })
            res.send({ status: 200, msg: 'ok', data: null })
        })
    }
}